package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.admin.AdminResult2;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.log.admin.LogAdminBan;
import com.yanqu.road.entity.mall.LimitBuyResult;
import com.yanqu.road.entity.platform.PlatformForbidden;
import com.yanqu.road.entity.player.PlayerState;
import com.yanqu.road.entity.player.UserAttribute;
import com.yanqu.road.entity.player.UserBagItem;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.servercenter.ChannelInfo;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.logic.bussiness.player.UserAttributeBussiness;
import com.yanqu.road.logic.bussiness.player.UserBagBussiness;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.server.agent.inter.AgentPlayer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.AttributeModule;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.gameplayer.module.player.PlayerModule;
import com.yanqu.road.server.gameplayer.module.player.RechargeModule;
import com.yanqu.road.server.logic.recharge.limit.BaseRMBMallLimit;
import com.yanqu.road.server.logic.recharge.limit.MallLimitFactory;
import com.yanqu.road.server.manger.*;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.*;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.GameChatControlMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.system.CommonMgr;
import com.yanqu.road.server.manger.system.PlatformGoodsMgr;
import com.yanqu.road.server.manger.thirdparty.PlatformMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.webservice.GamePublicFunction;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.TimeHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.controller.game.forbid.BanBase;
import com.yanqu.road.web.controller.game.forbid.IpBanned;
import com.yanqu.road.web.controller.game.sort.UserInfoEarnSpeedSort;
import com.yanqu.road.web.controller.game.sort.UserInfoLastLoginTimeSort;
import com.yanqu.road.web.controller.game.sort.UserInfoVipSort;
import com.yanqu.road.web.mgr.UserIdMgr;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/game/admin")
public class AdminFrontController {

    /**
     *  内服接口：1.6 内充购买项列表
     */
    @ResponseBody
    @RequestMapping(value = "playerCanBuyList", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String playerCanBuyList(HttpServletRequest request, @RequestBody String json){

        JSONObject jsonObject = JSONObject.parseObject(json);

        long playerId = jsonObject.getLongValue("playerId");
//        boolean isLoadPlayer = jsonObject.getBoolean("isLoadPlayer");
//
//        if(isLoadPlayer){
//            GamePlayerMgr.getPlayer(playerId);
//        }

        GamePlayer player = GamePlayerMgr.getPlayer(playerId);
        UserInfo userInfo;
        if (null == player) {
            userInfo = UserMgr.getUserInfo(playerId);
        } else {
            userInfo = player.getUserInfo();
        }
        if(userInfo == null){
            return AdminResult2.failMsg("playerId 不存在").toJsonString();
        }

        AdminResult2 result = AdminResult2.defaultInstance();

        List<Integer> mallCategoryList = new ArrayList<>();

        if (0 < ChannelConfig.THIRD_PARTY_RECHARGE_MARK) {//元宝类、特权卡类
            mallCategoryList.add(eMallCategory.Ingots.getValue());
            mallCategoryList.add(eMallCategory.PrivilegeCard.getValue());
            mallCategoryList.add(eMallCategory.TongBaoRecharge.getValue());
        }

        if (1 < ChannelConfig.THIRD_PARTY_RECHARGE_MARK) {//活动类礼包
            mallCategoryList.add(eMallCategory.Fund.getValue());
            mallCategoryList.add(eMallCategory.SecretVolume.getValue());
            mallCategoryList.add(eMallCategory.ZhanLingGiftBag.getValue());
            mallCategoryList.add(eMallCategory.PatronsFund.getValue());
        }
        List<JSONObject> tongbaoList = new ArrayList<>();
        TreeMap<Integer, JSONObject> resultMap = new TreeMap<>();
        for (Integer mallCategory : mallCategoryList) {
            List<MallInfo> mallInfoList = MallMgr.getMallInfoList(mallCategory);
            for (MallInfo mallInfo : mallInfoList) {
//                if(mallInfo.getRewardProp().getCountByGoodsId(110228).compareTo(BigInteger.ZERO) <= 0){
//                    continue;
//                }
                if(MallMgr.isSubscribeMall(mallInfo.getMallId())){//订阅商品不可以第三方
                    continue;
                }
                BaseRMBMallLimit baseRMBMallLimit = MallLimitFactory.getMallLimit(playerId, mallInfo, null);
                if (null != baseRMBMallLimit) {
                    if(0 == baseRMBMallLimit.checkMallLimit().getRet()){
                        JSONObject mallObj = parseMallObj(mallInfo, userInfo.getLanguage());
                        if(mallInfo.getRewardProp().getCountByGoodsId(110228).compareTo(BigInteger.ZERO) <= 0){
                            resultMap.put(mallInfo.getMallId(), mallObj);
                        }else {
                            tongbaoList.add(mallObj);
                        }
                    }
                }
            }
        }

        if(player != null) {
            //限时充值活动礼包
            boolean isUnlock = SystemOpenMgr.systemOpen(player, eSystemId.RechargeActivity.getValue());
            if(isUnlock) {
                List<MallInfo> mallInfoList = MallMgr.getMallInfoList(eMallCategory.RechargeGoods.getValue());
                List<ActivityInfo> activityInfoList = NormalActivityMgr.getRechargeActivityInfoList();
                for (MallInfo mallInfo : mallInfoList) {
//                    if(mallInfo.getRewardProp().getCountByGoodsId(110228).compareTo(BigInteger.ZERO) <= 0){
//                        continue;
//                    }
                    boolean isFind = false;
                    for (ActivityInfo activityInfo : activityInfoList) {
                        List<ActivityConditionInfo> activityConditionInfoList = NormalActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId());
                        if(null != activityConditionInfoList) {
                            for (ActivityConditionInfo activityConditionInfo : activityConditionInfoList) {
                                if ((eGamePlayerEventType.RechargeItem.getValue() == activityConditionInfo.getType() &&
                                        activityConditionInfo.getParamList().get(2).compareTo(BigInteger.valueOf(mallInfo.getMallId())) == 0)
                                        || GamePublicFunction.newRechargeCanFindMallInfo(activityConditionInfo, mallInfo.getMallId())) {
                                    BaseRMBMallLimit baseRMBMallLimit = MallLimitFactory.getMallLimit(playerId, mallInfo, activityInfo);
                                    if(null != baseRMBMallLimit){
                                        LimitBuyResult limitBuyResult = baseRMBMallLimit.checkMallLimit();
                                        if(0 == limitBuyResult.getRet()){
                                            if(activityInfo.getType() == eActivityType.NewRechargeActivity.getValue()
                                                    && activityInfo.getChildType() == eNewRechargeActivityType.ServerOpenGifts.getValue()
                                            ){
                                                JSONObject mallObj = parseMallObj(mallInfo, player.getLanguage());
                                                mallObj.put("limitNum", limitBuyResult.getLimitCount());
//                                                result.getData().add(mallObj);
                                                if(mallInfo.getRewardProp().getCountByGoodsId(110228).compareTo(BigInteger.ZERO) <= 0){
                                                    resultMap.put(mallInfo.getMallId(), mallObj);
                                                }else {
                                                    tongbaoList.add(mallObj);
                                                }
                                            }else {
                                                JSONObject mallObj = parseMallObj(mallInfo, activityConditionInfo, player.getLanguage());
                                                mallObj.put("limitNum", limitBuyResult.getLimitCount());
//                                                result.getData().add(mallObj);
                                                if(mallInfo.getRewardProp().getCountByGoodsId(110228).compareTo(BigInteger.ZERO) <= 0){
                                                    resultMap.put(mallInfo.getMallId(), mallObj);
                                                }else {
                                                    tongbaoList.add(mallObj);
                                                }
                                            }
                                            isFind = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (isFind) {
                            break;
                        }
                    }
                }
            }
        }

        //活动礼包
        Map<Integer, Map<Integer, MallInfo>> activityMallInfoMap = ActivityMgr.getAllActivityMallInfoMap();
        for(Map.Entry<Integer, Map<Integer, MallInfo>> dataEntry : activityMallInfoMap.entrySet()){
            for(MallInfo mallInfo : dataEntry.getValue().values()){
//                if(mallInfo.getRewardProp().getCountByGoodsId(110228).compareTo(BigInteger.ZERO) <= 0){
//                    continue;
//                }
                if(mallInfo.getRechargeId() > 0) {//有充值项编号的商品才是
                    LimitBuyResult limitBuyResult = GamePublicFunction.activityMallCanBuy(mallInfo.getActivityId(), mallInfo.getMallId(), playerId);
                    if (0 == limitBuyResult.getRet()) {
                        JSONObject mallObj = parseMallObj(mallInfo, userInfo.getLanguage());
                        mallObj.put("limitNum", limitBuyResult.getLimitCount());
//                        result.getData().add(mallObj);
                        if(mallInfo.getRewardProp().getCountByGoodsId(110228).compareTo(BigInteger.ZERO) <= 0){
                            resultMap.put(mallInfo.getMallId(), mallObj);
                        }else {
                            tongbaoList.add(mallObj);
                        }
                    }
                }
            }
        }

        for (JSONObject object : tongbaoList) {
            result.getData().add(object);
        }

        for (Map.Entry<Integer, JSONObject> entry : resultMap.entrySet()) {
            result.getData().add(entry.getValue());
        }


        return result.toJsonString();
    }

    /**
     * 内服接口：1.8 充值购买
     */
    @ResponseBody
    @RequestMapping(value = "playerBuy", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String playerBuy(HttpServletRequest request, @RequestBody String json){

        if(StringUtils.isNullOrEmpty(json)){
            return AdminResult2.failMsg("请求参数空").toJsonString();
        }

        JSONObject paramObject = JSONObject.parseObject(json);

        String orderId = paramObject.getString("orderId");

        if(!paramObject.containsKey("playerId")){
            return AdminResult2.failMsg("playerId 参数空").toJsonString();
        }
        long userId = paramObject.getLongValue("playerId");
        UserInfo userInfo = UserMgr.getUserInfo(userId);
        if(userInfo == null){
            return AdminResult2.failMsg("玩家不存在").toJsonString();
        }

        JSONArray items = paramObject.getJSONArray("mallList");
        if(items == null){
            return AdminResult2.failMsg("mallList 参数空").toJsonString();
        }

        List<String> failList = new ArrayList<>();
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if(player != null) {

            //检查订单处理标识
            //todo

            Property buyInfo = new Property();

            for (int i = 0; i < items.size(); i++) {
                JSONObject jo = items.getJSONObject(i);
                int mallId = jo.getIntValue("mallId");
                int num = jo.getIntValue("num");
                for (int i1 = 0; i1 < num; i1++) {
                    int ret = player.getModule(RechargeModule.class).backendRechargeMall(mallId);
                    if(ret == 0){
                        buyInfo.addProperty(mallId, BigInteger.ONE);
                    }else {
                        failList.add(mallId + "=" + (num - i1));
                        break;
                    }
                }
            }

            if(!buyInfo.isNothing()){
                //更新订单处理标识
                //todo

            }
        }else {
            AdminResult2.failMsg("玩家存在").toJsonString();
        }

        if(failList.size() > 0){
            AdminResult2 result2 = AdminResult2.failMsg("部分失败");
            result2.setCode(0);
            result2.getData().add(StringUtils.listToString(failList, ","));
            return result2.toJsonString();
        }

        AdminResult2 result = AdminResult2.defaultInstance();

        return result.toJsonString();
    }

    /**
     *  内服接口：1.1 角色检查
     */
    @ResponseBody
    @RequestMapping(value = "checkAccount", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String checkAccount(HttpServletRequest request, @RequestParam("userId") String user){

        List<Long> userIdList = StringUtils.stringToLongList(user, ",");

        userIdList.removeIf(uid -> UserMgr.getUserInfo(uid) != null);

        if(userIdList.isEmpty()){
            return AdminResult.defaultInstance().toJsonString();
        }

        AdminResult adminResult = AdminResult.defaultInstance();

        adminResult.getData().put("userIdList", userIdList);
        if(userIdList.size() > 0) {
            adminResult.setCode(-1);
            adminResult.setMsg("失败");
        }else {

        }

        return adminResult.toJsonString();
    }

    /**
     * 内服接口：1.4 内服角色查询
     */
    @ResponseBody
    @RequestMapping(value = "roleSearch", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String roleSearch(HttpServletRequest request, @RequestBody String json){

        JSONObject paramObject = JSONObject.parseObject(json);
        String userIdListParam = paramObject.getString("userIdList");

        if(StringUtils.isNullOrEmpty(userIdListParam)){
            return AdminResult.failMsg("userIdList 为空").toJsonString();
        }

        String openId = paramObject.getString("openId");
        String name = paramObject.getString("name");
        JSONArray registrationTime = paramObject.getJSONArray("registrationTime");

        JSONArray lastLoginTime = paramObject.getJSONArray("lastLoginTime");

        JSONArray level = paramObject.getJSONArray("level");

        JSONArray amountCharge = paramObject.getJSONArray("amountCharge");

        boolean isWhite = paramObject.getBooleanValue("isWhite");

        JSONArray locations = paramObject.getJSONArray("locations");

        int pageNum = paramObject.getIntValue("pageNum");
        int pageSize = paramObject.getIntValue("pageSize");

        AdminResult result = AdminResult.defaultInstance();

        long serverId = ConfigHelper.getLong("serverId");
        ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
        ChannelInfo channelInfo = ServerListMgr.getChannelInfo(serverInfo.getChannelId());

        List<Long> userIdList = StringUtils.stringToLongList(userIdListParam, ",");

        List<String> locationList = new ArrayList<>();
        if(locations != null){
            for (int i = 0; i < locations.size(); i++) {
                locationList.add(locations.getString(i));
            }
        }

        List<UserInfo> userInfoList = new ArrayList<>();
        for (int i = 0; i < userIdList.size(); i++) {
            long userId = userIdList.get(i);
            UserInfo userInfo = UserMgr.getUserInfo(userId);
            if(userInfo == null){
                continue;
            }
            if(!StringUtils.isNullOrEmpty(openId) && !userInfo.getOpenId().equals(openId)){
                continue;
            }
            if(!StringUtils.isNullOrEmpty(name) && !userInfo.getNickName().contains(name)){
                continue;
            }
            if(level != null && level.size() == 2){
                int start = level.getIntValue(0);
                int end = level.getIntValue(1);
                if(userInfo.getTitleId() < start || userInfo.getTitleId() > end){
                    continue;
                }
            }
            if(registrationTime != null && registrationTime.size() == 2){
                long start = getString2Date(registrationTime.getString(0)).getTime() / 1000;
                long end = getString2Date(registrationTime.getString(1)).getTime() / 1000;
                if(userInfo.getRegisterTime() < start || userInfo.getRegisterTime() > end){
                    continue;
                }
            }
            if(lastLoginTime != null && lastLoginTime.size() == 2){
                long start = getString2Date(lastLoginTime.getString(0)).getTime() / 1000;
                long end = getString2Date(lastLoginTime.getString(1)).getTime() / 1000;
                if(userInfo.getLastLoginTime() < start || userInfo.getLastLoginTime() > end){
                    continue;
                }
            }
            if(amountCharge != null && amountCharge.size() == 2){
                int start = amountCharge.getIntValue(0);
                int end = amountCharge.getIntValue(1);
                if(userInfo.getVipExp() < start || userInfo.getVipExp() > end){
                    continue;
                }
            }
            if(locationList.size() > 0 && !locationList.contains(userInfo.getIpLocation())){
                continue;
            }
            userInfoList.add(userInfo);
        }

        int startIndex = (pageNum - 1) * pageSize;
        startIndex = Math.max(0, startIndex);
        result.getData().put("total", userInfoList.size());
        JSONArray array = new JSONArray();
        for (int i = startIndex; i < startIndex + pageSize && i < userInfoList.size(); i++) {
            UserInfo userInfo = userInfoList.get(i);
            JSONObject object =  new JSONObject();
            object.put("userId", userInfo.getUserId());
            object.put("openId", userInfo.getOpenId());
            object.put("name", userInfo.getNickName());
            object.put("registerTime", userInfo.getRegisterTime());
            object.put("lastLoginTime", userInfo.getLastLoginTime());
            object.put("level", userInfo.getTitleId());
            object.put("amountCharge", userInfo.getVipExp());
            object.put("isWhite", PlatformUserIdMgr.isPlatformUserIdPass(userInfo.getPlatformUserId()));
            object.put("location", userInfo.getIpLocation());
            object.put("serverId", serverId);
            object.put("serverName", serverInfo.getServerName());
            object.put("channelId", serverInfo.getChannelId());
            object.put("channelName", eChannelType.forValue(channelInfo.getChannelId()).getName());
            object.put("status", getUserStatus(userInfo));
            object.put("banSpeakTime", userInfo.getForbiddenSpeakEndTime());
            object.put("bannedTime", userInfo.getBlackListEndTime());
            array.add(object);
        }
        result.getData().put("row", array);
        return result.toJsonString();
    }

    /**
     * 内服接口：1.5 修改状态
     */
    @ResponseBody
    @RequestMapping(value = "forbiddenPlayer", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String forbiddenPlayer(HttpServletRequest request, @RequestBody String json){

        JSONObject paramObject = JSONObject.parseObject(json);

        int status = paramObject.getIntValue("status");

        String forbiddenEndTime = paramObject.getString("forbiddenEndTime");

        String userId = paramObject.getString("userIdList");

        List<Long> userIdList = StringUtils.stringToLongList(userId, ",");

        AdminResult result = AdminResult.defaultInstance();

        for (Long uid : userIdList) {
            GamePlayer gamePlayer = GamePlayerMgr.getPlayer(uid);
            if(gamePlayer == null){
                result.getData().put(uid.toString(), false);
                continue;
            }
            if(status == 0){
                //禁用
                Date date = DateHelper.getString2Date(forbiddenEndTime);
                if(date != null){
                    gamePlayer.getUserInfo().setBlackListEndTime(date.getTime());
                    result.getData().put(uid.toString(), true);
                }else {
                    result.getData().put(uid.toString(), false);
                }
            }else if(status == 1){
                //启用
                gamePlayer.getUserInfo().setBlackListEndTime(System.currentTimeMillis());
                result.getData().put(uid.toString(), true);
            }
        }

        return result.toJsonString();
    }

    /**
     * 内服接口：1.7 内服用户修改定位
     */
    @ResponseBody
    @RequestMapping(value = "modifyLocation", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String modifyLocation(HttpServletRequest request, @RequestBody String json){

        JSONObject paramObject = JSONObject.parseObject(json);

        long userId = paramObject.getLongValue("userId");
        String location = paramObject.getString("location");

        GamePlayer gamePlayer = GamePlayerMgr.getPlayer(userId);
        if(gamePlayer != null){
            gamePlayer.getUserInfo().setIpLocation(location);
        }else {
            return AdminResult.failMsg("玩家不存在").toJsonString();
        }

        return AdminResult.defaultInstance().toJsonString();
    }

    private JSONObject parseMallObj(MallInfo mallInfo, ActivityConditionInfo activityConditionInfo, String language) {
        JSONObject object = parseMallObj(mallInfo, language);
        object.put("mallName", ServerLanguageMgr.getContent(activityConditionInfo.getDesc(), language));
        return object;
    }

    private JSONObject parseMallObj(MallInfo mallInfo, String language) {
        JSONObject object = new JSONObject();
        object.put("mallId", mallInfo.getMallId());
        object.put("mallName", MallMgr.getMallName(mallInfo, language));
        object.put("limitNum", mallInfo.getLimitBuyCount());
        long mallParamValue = MallRechargeConfigMgr.getParamValue(mallInfo);
        if(mallParamValue > 0){
            object.put("price", mallParamValue * 100);
        }else {
            long price = MallRechargeConfigMgr.getPrice(mallInfo);
            object.put("price", price);
        }
//        if(!StringUtils.isNullOrEmpty(mallInfo.getParam()) && !"0".equals(mallInfo.getParam())){
//            object.put("price", Integer.parseInt(mallInfo.getParam()) * 100);
//        }else {
//            object.put("price", mallInfo.getPrice());
//        }
        //特殊处理
        if(mallInfo.getMallMarkId() == 300001240){
            object.put("price", "1000");
        }else if(mallInfo.getMallMarkId() == 300001241){
            object.put("price", "3000");
        }else if(mallInfo.getMallMarkId() == 300001242){
            object.put("price", "6000");
        }else if(mallInfo.getMallMarkId() == 300001243){
            object.put("price", "10000");
        }else if(mallInfo.getMallMarkId() == 300001244){
            object.put("price", "20000");
        }else if(mallInfo.getMallMarkId() == 300001245){
            object.put("price", "40000");
        }else if(mallInfo.getMallMarkId() == 300001246){
            object.put("price", "60000");
        }else if(mallInfo.getMallMarkId() == 300001247){
            object.put("price", "100000");
        }else if(mallInfo.getMallMarkId() == 300001248){
            object.put("price", "600");
        }else if(mallInfo.getMallMarkId() == 300001249){
            object.put("price", "200000");
        }else if(mallInfo.getMallMarkId() == 300001160){
            object.put("price", "4100");
        }else if(mallInfo.getMallMarkId() == 300001161){
            object.put("price", "7400");
        }else if(mallInfo.getMallMarkId() == 300001162){
            object.put("price", "10900");
        }else if(mallInfo.getMallMarkId() == 300001163){
            object.put("price", "21800");
        }else if(mallInfo.getMallMarkId() == 300001164){
            object.put("price", "33200");
        }else if(mallInfo.getMallMarkId() == 300001165){
            object.put("price", "63900");
        }else if(mallInfo.getMallMarkId() == 300001166){
            object.put("price", "94400");
        }else if(mallInfo.getMallMarkId() == 300001167){
            object.put("price", "133300");
        }else if(mallInfo.getMallMarkId() == 300001168){
            object.put("price", "204400");
        }else if(mallInfo.getMallMarkId() == 300001169){
            object.put("price", "310000");
        }else if(mallInfo.getMallMarkId() == 300001170){
            object.put("price", "554400");
        }else if(mallInfo.getMallMarkId() == 300001171){
            object.put("price", "665600");
        }else if(mallInfo.getMallMarkId() == 300001172){
            object.put("price", "600");
        }else if(mallInfo.getMallMarkId() == 300001180){
            object.put("price", "300");
        }else if(mallInfo.getMallMarkId() == 300001181){
            object.put("price", "800");
        }else if(mallInfo.getMallMarkId() == 300001182){
            object.put("price", "4800");
        }else if(mallInfo.getMallMarkId() == 300001183){
            object.put("price", "9000");
        }else if(mallInfo.getMallMarkId() == 300001184){
            object.put("price", "12900");
        }else if(mallInfo.getMallMarkId() == 300001185){
            object.put("price", "26700");
        }else if(mallInfo.getMallMarkId() == 300001186){
            object.put("price", "41300");
        }else if(mallInfo.getMallMarkId() == 300001187){
            object.put("price", "77400");
        }else if(mallInfo.getMallMarkId() == 300001188){
            object.put("price", "119300");
        }else if(mallInfo.getMallMarkId() == 300001189){
            object.put("price", "170900");
        }else if(mallInfo.getMallMarkId() == 300001190){
            object.put("price", "258000");
        }else if(mallInfo.getMallMarkId() == 300001191){
            object.put("price", "387100");
        }else if(mallInfo.getMallMarkId() == 300001192){
            object.put("price", "645100");
        }else if(mallInfo.getMallMarkId() == 300001193){
            object.put("price", "806400");
        }else if(mallInfo.getMallMarkId() == 300001200){
            object.put("price", "5300");
        }else if(mallInfo.getMallMarkId() == 300001201){
            object.put("price", "9600");
        }else if(mallInfo.getMallMarkId() == 300001202){
            object.put("price", "14200");
        }else if(mallInfo.getMallMarkId() == 300001203){
            object.put("price", "28300");
        }else if(mallInfo.getMallMarkId() == 300001204){
            object.put("price", "43200");
        }else if(mallInfo.getMallMarkId() == 300001205){
            object.put("price", "83100");
        }else if(mallInfo.getMallMarkId() == 300001206){
            object.put("price", "122700");
        }else if(mallInfo.getMallMarkId() == 300001207){
            object.put("price", "173300");
        }else if(mallInfo.getMallMarkId() == 300001208){
            object.put("price", "265700");
        }else if(mallInfo.getMallMarkId() == 300001209){
            object.put("price", "403000");
        }else if(mallInfo.getMallMarkId() == 300001210){
            object.put("price", "720700");
        }else if(mallInfo.getMallMarkId() == 300001211){
            object.put("price", "865300");
        }else if(mallInfo.getMallMarkId() == 300001220){
            object.put("price", "800");
        }else if(mallInfo.getMallMarkId() == 300001221){
            object.put("price", "4900");
        }else if(mallInfo.getMallMarkId() == 300001222){
            object.put("price", "9400");
        }else if(mallInfo.getMallMarkId() == 300001223){
            object.put("price", "13900");
        }else if(mallInfo.getMallMarkId() == 300001224){
            object.put("price", "27200");
        }else if(mallInfo.getMallMarkId() == 300001225){
            object.put("price", "42800");
        }else if(mallInfo.getMallMarkId() == 300001226){
            object.put("price", "80600");
        }else if(mallInfo.getMallMarkId() == 300001227){
            object.put("price", "121700");
        }else if(mallInfo.getMallMarkId() == 300001228){
            object.put("price", "166100");
        }else if(mallInfo.getMallMarkId() == 300001229){
            object.put("price", "250000");
        }else if(mallInfo.getMallMarkId() == 300001230){
            object.put("price", "383300");
        }else if(mallInfo.getMallMarkId() == 300001231){
            object.put("price", "661100");
        }else if(mallInfo.getMallMarkId() == 300001232){
            object.put("price", "827800");
        }

        return object;
    }

    public static Date getString2Date(String dateStr) {
        Date date = null;
        try {
            SimpleDateFormat sdf = TimeHelper.getSimpleDateFormat(DateHelper.YMD_BAR);
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 玩家状态
     * banned：封号；
     * banSpeak 禁言；
     * trusteeship 托管；
     * disableEditName 禁止修改名称；
     * disableEditHead 禁止修改头像；
     * resetHead重置头像
     *
     */
    public List<String> getUserStatus(UserInfo userInfo){
        List<String> statusList = new ArrayList<>();
        long now = System.currentTimeMillis();
        if(userInfo.getForbiddenSpeakEndTime() > now){
            statusList.add("banSpeak");
        }
        if(userInfo.getBlackListEndTime() > now){
            statusList.add("banned");
        }
        if(userInfo.getBlackListEndTime() == 3){
            statusList.add("trusteeship");
        }
        return statusList;
    }

    /**
     * 2.6 重置头像
     */
    @ResponseBody
    @RequestMapping(value = "resetHeaderDecoration", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String resetHeaderDecoration(HttpServletRequest request, @RequestBody JSONObject json){

        JSONArray userIdList = json.getJSONArray("userIdList");
        for (int i = 0; i < userIdList.size(); i++) {
            long userId = userIdList.getLongValue(i);
            UserInfo userInfo = UserMgr.getUserInfoInRAM(userId);
            if(userInfo == null){
                continue;
            }
            List<Integer> dataList = StringUtils.stringToIntegerList(userInfo.getDecoration(), DecorationMgr.SPLIT_SEPARATOR);
            if (dataList.size() > 0) {
                dataList.set(0, DecorationMgr.getDefaultDecorationId(eDecorationType.HeadIcon.getValue(), userInfo.getSex()));
            }
            String decoration = StringUtils.listToString(dataList, DecorationMgr.SEPARATOR);
            userInfo.setDecoration(decoration);
            GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            if(onlinePlayer != null){
                onlinePlayer.getModule(PlayerModule.class).onUserInfoChange();
            }
        }

        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 2.7 用户改名
     */
    @ResponseBody
    @RequestMapping(value = "changeUserNickName", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String changeUserNickName(HttpServletRequest request, @RequestBody JSONObject json){

        Long userId = json.getLong("userId");
        UserInfo userInfo = UserMgr.getUserInfoInRAM(userId);
        if(userInfo == null){
            return AdminResult.failMsg("角色不存在").toJsonString();
        }

        String userName = json.getString("userName");

        userInfo.setNickName(userName);

        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if (player != null) {
            if (PlatformMgr.changeNickName(player, userName, false, false) != 0) {
                return AdminResult.failMsg(String.valueOf(eAgentErrorCode.NickNameError.getValue())).toJsonString();
            }else {
            }
        } else {
            boolean b = UserBussiness.updateNickName(userId, userName);
        }

        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 3.1 公告操作
     */

    @ResponseBody
    @RequestMapping(value = "channelNotice", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    public String channelNotice(HttpServletRequest request, @RequestBody String json){


        return AdminResult.defaultInstance().toJsonString();
    }


    /**
     * 2.1 角色查询
     */
    @ResponseBody
    @RequestMapping(value = "roleSearch2", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String roleSearch2(HttpServletRequest request, @RequestBody JSONObject paramObject){

        List<UserInfo> userInfoList = new ArrayList<>();

        String userId = paramObject.getString("userId");
        String openId = paramObject.getString("openId");
        long userAliasId = paramObject.getLongValue("userAliasId"); // 游戏编号
        if(!StringUtils.isNullOrEmpty(userId)){
            UserInfo userInfo = UserMgr.getUserInfo(Long.parseLong(userId));
            if(userInfo != null){
                userInfoList.add(userInfo);
            }
        }else if(!StringUtils.isNullOrEmpty(openId)){
            List<UserInfo> list = UserMgr.getUserInfoByOpenId(openId);
            userInfoList.addAll(list);
        } else if (userAliasId > 0L) {
            UserInfo userInfo = UserMgr.getUserInfoByUserAliasId(userAliasId);
            if(userInfo != null){
                userInfoList.add(userInfo);
            }
        } else {

            String orderSort = "desc";
            String orderByColumn = paramObject.getString("orderByColumn");
            if(paramObject.containsKey("orderSort")){
                orderSort = paramObject.getString("orderSort");
            }
            Comparator<UserInfo> sortor = new UserInfoEarnSpeedSort(orderSort);
            if("lastLoginTime".equals(orderByColumn)){
                sortor = new UserInfoLastLoginTimeSort(orderSort);
            }else if("exp".equals(orderByColumn)){
                sortor = new UserInfoVipSort(orderSort);
            }

            String appId = paramObject.getString("appId");

            String name = paramObject.getString("name");

            JSONArray registrationTime = paramObject.getJSONArray("registrationTime");

            JSONArray lastLoginTime = paramObject.getJSONArray("lastLoginTime");

            //最后充值时间 todo
            JSONArray lastRechargeTime = paramObject.getJSONArray("lastRechargeTime");

            JSONArray status = paramObject.getJSONArray("status");

            //
            boolean isWhite = paramObject.getBooleanValue("isWhite");

            String platformUserId = "";
            if(paramObject.containsKey("platformUserId")){
                platformUserId = paramObject.getString("platformUserId");
            }

            List<UserInfo> list = UserMgr.getUserInfoList();
            list.sort(sortor);

            int size = list.size();
            for (int i = 0; i < size; i++) {
                UserInfo userInfo = list.get(i);

                if(!StringUtils.isNullOrEmpty(appId) && !appId.equals(userInfo.getAppId())){
                    continue;
                }

                if(!StringUtils.isNullOrEmpty(name) && !userInfo.getNickName().contains(name)){
                    continue;
                }

                if(!StringUtils.isNullOrEmpty(platformUserId) && !userInfo.getPlatformUserId().contains(platformUserId)){
                    continue;
                }

                if(registrationTime != null && registrationTime.size() == 2){
                    long start = getString2Date(registrationTime.getString(0)).getTime() / 1000;
                    long end = getString2Date(registrationTime.getString(1)).getTime() / 1000;
                    if(userInfo.getRegisterTime() < start || userInfo.getRegisterTime() > end){
                        continue;
                    }
                }

                if(lastLoginTime != null && lastLoginTime.size() == 2){
                    long start = getString2Date(lastLoginTime.getString(0)).getTime() / 1000;
                    long end = getString2Date(lastLoginTime.getString(1)).getTime() / 1000;
                    if(userInfo.getLastLoginTime() < start || userInfo.getLastLoginTime() > end){
                        continue;
                    }
                }

                if(status != null){
                    long now = System.currentTimeMillis();
                    boolean next = false;
                    for (int i1 = 0; i1 < status.size(); i1++) {
                        String s = status.getString(i1);
                        if("banned".equals(s)){
                            if(userInfo.getBlackListEndTime() < now){
                                next = true;
                                break;
                            }
                        }
                    }
                    if(next){
                        continue;
                    }
                }

                userInfoList.add(userInfo);
            }

        }

        int pageNum = paramObject.getIntValue("pageNum");

        int pageSize = paramObject.getIntValue("pageSize");


        AdminResult result = AdminResult.defaultInstance();

        long serverId = ConfigHelper.getLong("serverId");
        ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
        ChannelInfo channelInfo = ServerListMgr.getChannelInfo(serverInfo.getChannelId());


        int startIndex = (pageNum - 1) * pageSize;
        startIndex = Math.max(0, startIndex);
        result.getData().put("total", userInfoList.size());
        JSONArray array = new JSONArray();
        for (int i = startIndex; i < startIndex + pageSize && i < userInfoList.size(); i++) {
            UserInfo userInfo = userInfoList.get(i);
            JSONObject object =  new JSONObject();
            object.put("userId", userInfo.getUserId());
            object.put("openId", userInfo.getOpenId());
            object.put("name", userInfo.getNickName());
            object.put("power", userInfo.getEarnSpeed().toString());
            object.put("registerTime", DateHelper.getCurrentDateTimeString(userInfo.getRegisterTime() * 1000));
            object.put("lastLoginTime", DateHelper.getCurrentDateTimeString(userInfo.getLastLoginTime() * 1000));
            object.put("status", getUserStatus(userInfo));
            object.put("amountCharge", userInfo.getVipExp() * 100);
            object.put("lastLoginIp", "");
            object.put("clan", "");
            object.put("platformUserId", userInfo.getPlatformUserId());
            object.put("userAliasId", userInfo.getUserAliasId());
            object.put("isWhite", PlatformUserIdMgr.isPlatformUserIdPass(userInfo.getPlatformUserId()));
//            object.put("lastRechargeTime", )
            if(userInfoList.size() < 10){
                UserAttribute userAttribute = UserAttributeBussiness.getUserAttribute(userInfo.getUserId(), ePlayerAttrType.LastRechargeTime);
                if(userAttribute != null && userAttribute.getValue() > 0){
                    object.put("lastRechargeTime", DateHelper.getCurrentDateTimeString(userAttribute.getValue() * 1000));
                }
            }
            if(!StringUtils.isNullOrEmpty(userInfo.getUnionUid())){
                CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(userInfo.getUnionUid());
                if(unionInfo != null){
                    object.put("clan", unionInfo.getUnionName());
                }
            }
            object.put("location", userInfo.getIpLocation());

            GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userInfo.getUserId());
            if(onlinePlayer != null){

                object.put("lastLoginIp", onlinePlayer.getIp());
                if(onlinePlayer.getState() == PlayerState.ONLINE){
                    object.put("onlineStatus", true);
                }else {
                    object.put("onlineStatus", false);
                }
            }

            object.put("channelId", serverInfo.getChannelId());
            object.put("appId", userInfo.getAppId());
            object.put("level", userInfo.getTitleId());
            object.put("location", userInfo.getIpLocation());
            object.put("serverId", serverId);
            object.put("serverName", serverInfo.getServerName());
            object.put("channelName", eChannelType.forValue(channelInfo.getChannelId()).getName());

            object.put("lv", VipMgr.getVipLv(userInfo.getVipExp()));
            object.put("exp", userInfo.getVipExp());
            array.add(object);
        }

        result.getData().put("row", array);
        return result.toJsonString();

    }


    /**
     * 2.2 角色状态修改
     */
    @ResponseBody
    @RequestMapping(value = "roleModify", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String roleModify(HttpServletRequest request, @RequestBody JSONObject paramObject) {
        String status = paramObject.getString("status");
        String statusType = paramObject.getString("statusType");
        String statusTime = paramObject.getString("statusTime");
        int clearChat = paramObject.getIntValue("isClearChat");
        long time = DateHelper.str2timestamp(statusTime);

        long serverId = paramObject.getLong("serverId");
        int channelId = ServerListMgr.getChannelId(serverId);

        JSONArray mailNotice = paramObject.getJSONArray("mailNotice");
        Map<String, List<String>> mailMap = new HashMap<>(); // language -> (title,content)
        if (mailNotice != null) {
            for (Object obj : mailNotice) {
                JSONObject jsonObject = (JSONObject) obj;
                mailMap.put(jsonObject.getString("language"), Arrays.asList(jsonObject.getString("title"), jsonObject.getString("content")));
            }
        }


        JSONArray userIdList = paramObject.getJSONArray("userIdList");
        List<Long> userIds = new ArrayList<>();
        List<String> ips = new ArrayList<>();
        if (status.equals(ePlatformForbiddenType.IP_BANNED.getName())) { // 在这种类型中，同时userIdList里放的是ip地址
            for (int i = 0; i < userIdList.size(); i++) {
                ips.add(userIdList.getString(i));
            }
            for (String ip : ips) {
                if (StringUtils.isNullOrEmpty(ip)) {
                    continue;
                }

                IpBanned ipBanned = new IpBanned(ip, time);
                AdminResult result;
                if ("true".equals(statusType)) {
                    result = ipBanned.ban();
                } else {
                    result = ipBanned.unban();
                }
                if (result.getCode() == -1) {
                    return result.toJsonString();
                }
            }
        } else {
            for (int i = 0; i < userIdList.size(); i++) {
                userIds.add(userIdList.getLongValue(i));
            }
            for (Long userId : userIds) {
                UserInfo userInfo = UserMgr.getUserInfo(userId);
                if (userInfo == null) {
                    continue;
                }

                BanBase banBase = BanBase.getBanInstance(status, userId, time);
                if (banBase == null) {
                    return AdminResult.failMsg("无效的封禁类型").toJsonString();
                }
                banBase.setMailMap(mailMap);
                if ("true".equals(statusType)) {
                    AdminResult result = banBase.ban();
                    if (result.getCode() == -1) {
                        return result.toJsonString();
                    }
                    if (clearChat == 1) {
                        AdminResult result1 = BanBase.clearChat(userId, serverId, channelId, time);
                        if (result1.getCode() == -1) {
                            return result1.toJsonString();
                        }
                    }
                    AutoLogMgr.add(new LogAdminBan(userId, status, System.currentTimeMillis(), time, 1, clearChat));
                } else {
                    AdminResult result = banBase.unban();
                    if (result.getCode() == -1) {
                        return result.toJsonString();
                    }
                    AutoLogMgr.add(new LogAdminBan(userId, status, System.currentTimeMillis(), time, 0, clearChat));
                }
            }
        }

        if (clearChat == 1) { // 通知屏蔽聊天
            ChatControlMgr.reloadChatControl(channelId);
            GameChatControlMgr.syncOnlineUser();
        }

        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 2.3 角色强制下线
     */
    @ResponseBody
    @RequestMapping(value = "roleOffline", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String roleOffline(HttpServletRequest request, @RequestBody JSONObject paramObject){

        List<Long> userIds = new ArrayList<>();
        JSONArray userIdList = paramObject.getJSONArray("userIdList");
        for (int i = 0; i < userIdList.size(); i++) {
            userIds.add(userIdList.getLongValue(i));
        }

        for (Long userId : userIds) {
            GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            if(onlinePlayer != null){
                AgentPlayer.executeKillPlayer(userId);
            }
        }

        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 2.11 托管
     */
    @ResponseBody
    @RequestMapping(value = "role/trusteeship", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String roleTrusteeship(HttpServletRequest request, @RequestBody JSONObject jsonParam){

        long userId = jsonParam.getLongValue("userId");
        UserInfo userInfoInRAM = UserMgr.getUserInfoInRAM(userId);
        if(userInfoInRAM == null){
            return AdminResult.failMsg("用户不存在").toJsonString();
        }

        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (onlinePlayer != null) {
            UserInfo uInfo = onlinePlayer.getUserInfo();
            uInfo.setBlackListEndTime(3);
        } else {
            boolean b = UserBussiness.updateForbid(userId, 3);
            if(b){
                userInfoInRAM.setBlackListEndTime(3);
            }
        }

        if(onlinePlayer != null){
            AgentPlayer.executeKillPlayer(userId);
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 2.12 取消托管
     */
    @ResponseBody
    @RequestMapping(value = "role/cancelTrusteeship", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String roleCancelTrusteeship(HttpServletRequest request, @RequestBody JSONObject jsonParam){

        long userId = jsonParam.getLongValue("userId");
        UserInfo userInfoInRAM = UserMgr.getUserInfoInRAM(userId);
        if(userInfoInRAM == null){
            return AdminResult.failMsg("用户不存在").toJsonString();
        }
        long blackForbiddenTime = System.currentTimeMillis();
        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (onlinePlayer != null) {
            UserInfo uInfo = onlinePlayer.getUserInfo();
            uInfo.setBlackListEndTime(blackForbiddenTime);
        } else {
            boolean b = UserBussiness.updateForbid(userId, blackForbiddenTime);
            if(b){
                userInfoInRAM.setBlackListEndTime(blackForbiddenTime);
            }
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 2.13 角色详情
     */
    @ResponseBody
    @RequestMapping(value = "character/detail", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String characterDetail(HttpServletRequest request, @RequestBody JSONObject paramObject){

        UserInfo userInfo = null;
        String userId = paramObject.getString("userId");
        if(!StringUtils.isNullOrEmpty(userId)){
            userInfo = UserMgr.getUserInfo(Long.parseLong(userId));
        }
        if (userInfo == null){
            return AdminResult.failMsg("").toJsonString();
        }

        AdminResult result = AdminResult.defaultInstance();

        long serverId = ConfigHelper.getLong("serverId");
        ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
        ChannelInfo channelInfo = ServerListMgr.getChannelInfo(serverInfo.getChannelId());

        JSONObject object =  new JSONObject();
        object.put("userId", userInfo.getUserId());
        object.put("openId", userInfo.getOpenId());
        object.put("name", userInfo.getNickName());
        object.put("power", userInfo.getEarnSpeed().toString());
        object.put("registerTime", DateHelper.getCurrentDateTimeString(userInfo.getRegisterTime() * 1000));
        object.put("lastLoginTime", DateHelper.getCurrentDateTimeString(userInfo.getLastLoginTime() * 1000));
        object.put("status", getUserStatus(userInfo));
        object.put("amountCharge", userInfo.getVipExp());
        object.put("lastLoginIp", "");
        object.put("isWhite", PlatformUserIdMgr.isPlatformUserIdPass(userInfo.getPlatformUserId()));

        UserAttribute userAttribute = UserAttributeBussiness.getUserAttribute(userInfo.getUserId(), ePlayerAttrType.LastRechargeTime);
        if(userAttribute != null && userAttribute.getValue() > 0){
            object.put("lastRechargeTime", DateHelper.getCurrentDateTimeString(userAttribute.getValue() * 1000));
        }
        Map<String, Object> gameMoneyMap = new HashMap<>();
        UserAttribute ingotsAttribute = UserAttributeBussiness.getUserAttribute(userInfo.getUserId(), ePlayerAttrType.Ingots);
        if(ingotsAttribute != null){
            gameMoneyMap.put("propId", GameConfig.GAME_MONEY_INGOTS);
            gameMoneyMap.put("num", ingotsAttribute.getValue());
        }

        object.put("gameMoney", gameMoneyMap);

        object.put("location", userInfo.getIpLocation());

        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userInfo.getUserId());
        if(onlinePlayer != null){

            object.put("lastLoginIp", onlinePlayer.getIp());
            if(onlinePlayer.getState() == PlayerState.ONLINE){
                object.put("onlineStatus", true);
            }else {
                object.put("onlineStatus", false);
            }
        }

        object.put("channelId", serverInfo.getChannelId());
        object.put("appId", userInfo.getAppId());
        object.put("level", userInfo.getTitleId());
        object.put("location", userInfo.getIpLocation());
        object.put("serverId", serverId);
        object.put("serverName", serverInfo.getServerName());
        object.put("channelName", eChannelType.forValue(channelInfo.getChannelId()).getName());

        object.put("lv", VipMgr.getVipLv(userInfo.getVipExp()));
        object.put("exp", userInfo.getVipExp());

        object.put("profilePicture", "");

        Map<Integer, UserBagItem> userBagItemMap;
        if(onlinePlayer != null){
            userBagItemMap = onlinePlayer.getModule(BagModule.class).getUserBagItemMap();
        }else {
            userBagItemMap = UserBagBussiness.getUserBagItemMap(userInfo.getUserId());
        }
        List<Map<String, Object>> packageDetail = new ArrayList<>();
        for (Map.Entry<Integer, UserBagItem> entry : userBagItemMap.entrySet()) {
            UserBagItem bagItem = entry.getValue();
//            if(bagItem.getNum() > 0){
                Map<String, Object> map = new HashMap<>();
                map.put("propId", bagItem.getGoodsId());
                if(CommonMgr.getGoodsInfo(bagItem.getGoodsId()) == null && PlatformGoodsMgr.getGoodsInfo(bagItem.getGoodsId()) == null) {
                    map.put("propName", GoodsMgr.getLocalGoodsName(bagItem.getGoodsId(), userInfo.getLanguage()));
                } else {
                    GoodsInfo goodsById = GoodsMgr.getGoodsById(bagItem.getGoodsId());
                    if(goodsById != null) {
                        map.put("propName", ServerLanguageMgr.getContent(goodsById.getGoodsName(), userInfo.getLanguage()));
                    }
                }
                map.put("propNum", bagItem.getNum());
                packageDetail.add(map);
//            }
        }
        object.put("packageDetail", packageDetail);
        result.setData(object);
        return result.toJsonString();

    }

    /**
     * 2.14 背包修改
     */
    @ResponseBody
    @RequestMapping(value = "role/packageChange", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String rolePackageChange(HttpServletRequest request, @RequestBody JSONObject jsonParam){

        if(!jsonParam.containsKey("serverId") || !jsonParam.containsKey("userId")){
            return AdminResult.failMsg("参数缺失").toJsonString();
        }
        long serverId = jsonParam.getLongValue("serverId");
        long userId = jsonParam.getLongValue("userId");
        int isAllowNegative = jsonParam.getIntValue("isAllowNegative");

        JSONArray detail = jsonParam.getJSONArray("packageChangeDetailMapList");
        UserInfo userInfoInRAM = UserMgr.getUserInfoInRAM(userId);
        if(userInfoInRAM == null){
            return AdminResult.failMsg("用户不存在").toJsonString();
        }
        if(userInfoInRAM.getBlackListEndTime() != 3){
            return AdminResult.failMsg("请先托管玩家").toJsonString();
        }
        AdminResult result = AdminResult.defaultInstance();
        Map<Integer, UserBagItem> userBagItemMap = UserBagBussiness.getUserBagItemMap(userId);
        long modifyTime = System.currentTimeMillis() / 1000;
        for (int i = 0; i < detail.size(); i++) {
            JSONObject jsonObject = detail.getJSONObject(i);
            int propId = jsonObject.getIntValue("propId");
            long changeNum = jsonObject.getLongValue("changeNum");
            GoodsInfo goodsInfo = GoodsMgr.getGoodsById(propId);
            if(goodsInfo == null){
                GoodsMgr.getLogger().debug("道具{} 配置不存在", propId);
                continue;
            }
            UserBagItem bagItem = userBagItemMap.get(propId);
            if(bagItem == null){
                bagItem = new UserBagItem();
                bagItem.setInsertOption();
                bagItem.setGoodsId(propId);
                bagItem.setUserId(userId);
            }
            if(isAllowNegative == 0 && bagItem.getNum() + changeNum < 0){
                changeNum = 0 - bagItem.getNum();
            }
            bagItem.setNum(bagItem.getNum() + changeNum);
            bagItem.setModifyTime(modifyTime);
            if(bagItem.isInsertOption()){
                UserBagBussiness.addUserBagItem(bagItem);
            }else {
                UserBagBussiness.updateUserBagItem(bagItem);
            }
        }
        return result.toJsonString();
    }

    /**
     * 2.18 封禁列表  获取角色封禁状态
     */
    @ResponseBody
    @RequestMapping(value = "getUserForbiddenStatus", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getUserForbiddenStatus(HttpServletRequest request, @RequestBody JSONObject paramObject) {
        Long userId = paramObject.getLong("userId");
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if (player == null) {
            return AdminResult2.failMsg("玩家不存在").toJsonString();
        }
        UserInfo userInfo = player.getUserInfo();
        if (userInfo == null) {
            return AdminResult2.failMsg("玩家信息未找到").toJsonString();
        }
        String platformUserId = userInfo.getPlatformUserId();

        AdminResult2 result = AdminResult2.defaultInstance();

        int totalCnt = 0; // 总的封禁次数
        Map<String, Map<Integer, PlatformForbidden>> map = ForbiddenMgr.getForbiddenPlatformUserIdMap();
        if (map.containsKey(platformUserId)) {
            Map<Integer, PlatformForbidden> userMap = map.get(platformUserId);
            for (PlatformForbidden data : userMap.values()) {
                JSONObject jsonObject = new JSONObject();
                ePlatformForbiddenType type = com.yanqu.road.entity.enums.ePlatformForbiddenType.forType(data.getForbiddenType());
                if (type == null) {
                    continue;
                }
                long forbiddenEndTime = data.getForbiddenTime();

                jsonObject.put("banType", type.getName());
                jsonObject.put("banTime", data.getForbiddenStartTime());
                jsonObject.put("unbanTime", data.getForbiddenTime());
                if (System.currentTimeMillis() < forbiddenEndTime) { // 封禁时间未到期
                    result.getData().add(jsonObject);
                }
                totalCnt += data.getTimes();
            }
        }
        result.setHistoryBanTimes(totalCnt);

        return result.toJsonString();
    }

    /**
     * 2.21 元宝修改 （2024.11.13 更新）
     */
    @ResponseBody
    @RequestMapping(value = "role/ingots/modify", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String ingotsModify(HttpServletRequest request, @RequestBody JSONObject jsonParam){

        if(!jsonParam.containsKey("serverId") || !jsonParam.containsKey("userId")){
            return AdminResult.failMsg("参数缺失").toJsonString();
        }

        int changeNum = jsonParam.getIntValue("changeNum");

        long userId = jsonParam.getLongValue("userId");

        UserInfo userInfoInRAM = UserMgr.getUserInfoInRAM(userId);
        if(userInfoInRAM == null){
            return AdminResult.failMsg("玩家不存在").toJsonString();
        }

        Property property = new Property();
        property.addProperty(GameConfig.GAME_MONEY_INGOTS, changeNum);
        synchronized (GamePlayerMgr.getPlayerLock(userId)) {
            GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            if(onlinePlayer != null){
                long ingots = onlinePlayer.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.Ingots);
                AttributeModule atModule = onlinePlayer.getModule(AttributeModule.class);
                atModule.onDataChange(ePlayerAttrType.Ingots);
                atModule.addAttribute(ePlayerAttrType.Ingots, changeNum);
                atModule.addAttribute(ePlayerAttrType.TotalIngots, changeNum);
                LogMgr.addLogIngots(onlinePlayer.getUserId(), changeNum, true, eLogMoneyType.GM, eLogMoneyType.BagBackendChange, ingots,
                        atModule.getAttribute(ePlayerAttrType.Ingots), "", onlinePlayer.getUserInfo().getVipExp());
            }else {
                Map<ePlayerAttrType, UserAttribute> userAttributeMap = UserAttributeBussiness.getUserAttributeMap(userId);
                UserAttribute attribute = userAttributeMap.get(ePlayerAttrType.Ingots);
                if(attribute == null){
                    attribute =new UserAttribute();
                    attribute.setUserId(userId);
                    attribute.setType(ePlayerAttrType.Ingots);
                    attribute.setInsertOption();
                }
                long ingots = attribute.getValue();
                attribute.setLastUpdateTime(System.currentTimeMillis());
                attribute.setValue(attribute.getValue() + changeNum);

                boolean result = false;
                if(attribute.isInsertOption()){
                    result = UserAttributeBussiness.addUserAttribute(attribute);
                }else if(attribute.isUpdateOption()){
                    result = UserAttributeBussiness.updateUserAttribute(attribute);
                }

                if(result) {
                    LogMgr.addLogIngots(userId, changeNum, true, eLogMoneyType.GM, eLogMoneyType.BagBackendChange, ingots,
                            attribute.getValue(), "", userInfoInRAM.getVipExp());
                }

                attribute = userAttributeMap.get(ePlayerAttrType.TotalIngots);
                if(attribute == null){
                    attribute =new UserAttribute();
                    attribute.setUserId(userId);
                    attribute.setType(ePlayerAttrType.TotalIngots);
                    attribute.setInsertOption();
                }

                attribute.setLastUpdateTime(System.currentTimeMillis());
                attribute.setValue(attribute.getValue() + changeNum);


                if(attribute.isInsertOption()){
                    UserAttributeBussiness.addUserAttribute(attribute);
                }else if(attribute.isUpdateOption()){
                    UserAttributeBussiness.updateUserAttribute(attribute);
                }
            }
        }

        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 2.15 批量背包修改
     */
    @ResponseBody
    @RequestMapping(value = "role/packageChange2", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String rolePackageChange2(HttpServletRequest request, @RequestBody JSONObject jsonParam){

        if(!jsonParam.containsKey("serverId") || !jsonParam.containsKey("userId")){
            return AdminResult.failMsg("参数缺失").toJsonString();
        }
        long userId = jsonParam.getLongValue("userId");
        int isAllowNegative = jsonParam.getIntValue("isAllowNegative");

        String updateContent = jsonParam.getString("updateContent");
        UserInfo userInfoInRAM = UserMgr.getUserInfoInRAM(userId);
        if(userInfoInRAM == null){
            return AdminResult.failMsg("用户不存在").toJsonString();
        }
        AdminResult result = AdminResult.defaultInstance();

        if(userInfoInRAM.getBlackListEndTime() != 3){
            return AdminResult.failMsg("请先托管玩家").toJsonString();
        }

        Map<Integer, UserBagItem> userBagItemMap = UserBagBussiness.getUserBagItemMap(userId);
        long modifyTime = System.currentTimeMillis() / 1000;
        updateContent = updateContent.replace("|", ";");
        Property property = PropertyHelper.parseStringToProperty(updateContent);
        for (Map.Entry<Integer, BigInteger> entry : property.getGoods().entrySet()) {
            int propId = entry.getKey();
            long changeNum = entry.getValue().longValue();
            GoodsInfo goodsInfo = GoodsMgr.getGoodsById(propId);
            if(goodsInfo == null){
                GoodsMgr.getLogger().debug("道具{} 配置不存在", propId);
                continue;
            }
            UserBagItem bagItem = userBagItemMap.get(propId);
            if(bagItem == null){
                bagItem = new UserBagItem();
                bagItem.setInsertOption();
                bagItem.setGoodsId(propId);
                bagItem.setUserId(userId);
            }
            if(isAllowNegative == 0 && bagItem.getNum() + changeNum < 0){
                changeNum = 0 - bagItem.getNum();
            }
            bagItem.setNum(bagItem.getNum() + changeNum);
            bagItem.setModifyTime(modifyTime);
            if(bagItem.isInsertOption()){
                UserBagBussiness.addUserBagItem(bagItem);
            }else {
                UserBagBussiness.updateUserBagItem(bagItem);
            }
        }
        return result.toJsonString();
    }

    /**
     * 2.19 vip经验修改
     */
    @ResponseBody
    @RequestMapping(value = "role/vip", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String vip(HttpServletRequest request, @RequestBody JSONObject jsonParam){
        long serverId = jsonParam.getIntValue("serverId");
        if(serverId <= 0){
            return AdminResult.failMsg("区服参数缺失").toJsonString();
        }
        long userId = jsonParam.getLongValue("userId");
        UserInfo userInfoInRAM = UserMgr.getUserInfoInRAM(userId);
        if(userInfoInRAM == null){
            return AdminResult.failMsg("玩家不存在").toJsonString();
        }
        int vipExpChange = jsonParam.getIntValue("vipExpChange");
        int vipExpDailyStoredChange = jsonParam.getIntValue("vipExpDailyStoredChange");
        int vipExpAllStoredChange = jsonParam.getIntValue("vipExpAllStoredChange");

        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if(player != null){
            if(vipExpChange != 0) {
                player.getModule(PlayerModule.class).changeVipExpBackend(vipExpChange);
            }
            if(vipExpAllStoredChange != 0){
                player.getModule(PlayerModule.class).changeTotalRechargeBackend(vipExpAllStoredChange);
            }
            if(vipExpDailyStoredChange != 0){
                player.getModule(PlayerModule.class).changeDayRechargeBackend(vipExpDailyStoredChange);
            }
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 2.24 修改头衔
     */
    @ResponseBody
    @RequestMapping(value = "role/titleChange", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String titleChange(HttpServletRequest request, @RequestBody JSONObject jsonParam){
        long userId = jsonParam.getLongValue("userId"); // 用户ID
        int titleLevel = jsonParam.getIntValue("titleLevel"); // 头衔等级

        if (TitleMgr.getTitleInfo(titleLevel) == null) {
            return AdminResult.failMsg("不存在的头衔等级").toJsonString();
        }

        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if (player == null) {
            return AdminResult.failMsg("用户不存在").toJsonString();
        }
        PlayerModule module = player.getModule(PlayerModule.class);
        module.getUserInfo().setTitleId(titleLevel);
        module.onTitleChange();
        module.onUserInfoChange();

        PlayerProto.TitleUpgradeRespMsg.Builder respMsg = PlayerProto.TitleUpgradeRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setTitleId(player.getTitleId());
        player.sendPacket(Protocol.U_TITLE_UPGRADE, respMsg);

        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     *  4.8 读取区服人数
     */
    @ResponseBody
    @RequestMapping(value = "getServerUserCountInfo", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getServerUserCountInfo(HttpServletRequest request) {

        JSONObject object = new JSONObject();
        object.put("serverId", ConfigHelper.getLong("serverId"));
        object.put("onlineCount", GamePlayerMgr.getCopyPlayerList().size());
        object.put("createCount", UserMgr.getRegisterNum());
        object.put("effectiveAngleCreation", UserIdMgr.getTotalRoleCreateCount2());

        int rechargeCount = 0; // 付费人数
        Map<Long, UserInfo> userInfoMap = UserBussiness.getUserInfoMap();
        for (UserInfo user : userInfoMap.values()) {
            if (user.getVipExp() > 0) {
                rechargeCount++;
            }
        }
        object.put("rechargeCount", rechargeCount);

        return object.toJSONString();
    }

    /**
     * 52.2 区服角色残留查询
     */
    @ResponseBody
    @RequestMapping(value = "alarm/queryServerRoleResidual", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String queryServerRoleResidual(HttpServletRequest request, @RequestBody JSONObject paramObject){
        AdminResult adminResult = new AdminResult();
        adminResult.getData().put("num", UserMgr.getUserInfoList().size());
        return adminResult.toJsonString();
    }
}
